import defaultImg from 'static/defaultImg/defaultCertificates.png'
import {
    uploadImgBusinessLicense,
    submitEnterpriseInfo,
    OCRRecognition,
    getBusinessIdttyWsid,
    getLegalPersonInfo
} from 'services/EnterpriseCertificationInformationService'
import base64TOFile from 'utils/base64ToFile'
export default {
    namespaces: 'EnterpriseCertificationInformationModel',
    state: {
        defaultImgUrl: defaultImg,
        imgUrl: '',
        agent: 'LEGAL_PERSON_AUTH',
        RealNameCertificationState: '',
        name: '',  //企业名称
        regNum: '',  //企业信用识别码
        legalName: '', //法人姓名
        legalIDCard: '',  //法人身份证
        idttyWsid: '',
        registerName: ''  //注册时的企业名称
    },
    reducers: {
        getRegisterName(state, { payload }) {
            return {
                ...state,
                registerName: payload
            }
        },
        setIdttyWsid(state, { payload }) {
            return {
                ...state,
                idttyWsid: payload
            }
        },
        changeImgUrl(state, { payload }) {
            return {
                ...state,
                imgUrl: 'data:image/png;base64,' + payload
            }
        },
        setLegalInfo(state, { payload }) {
            let { idCardNo, name } = payload
            return {
                ...state,
                legalName: name,
                legalIDCard: idCardNo
            }
        },
        switchAgent(state, payload) {
            let { agent } = state
            agent = agent === 'LEGAL_PERSON_AUTH' ? 'AGENT_PERSON_AUTH' : 'LEGAL_PERSON_AUTH'
            return {
                ...state,
                agent
            }
        },
        //修改RealNameCertificationState
        setRealNameCertificationState(state, { payload }) {
            return {
                ...state,
                RealNameCertificationState: payload
            }
        },
        //修改企业名称和统一信用识别码和imgUrl
        changeBussinessInfoAndImgUrl(state, { payload }) {
            let { name, regNum, imgUrl, idttyWsid } = payload
            return {
                ...state,
                name,
                regNum,
                imgUrl: 'data:image/png;base64,' + imgUrl,
                idttyWsid
            }
        }
    },
    effects: {
        //用于上传图片
        *upLoadImg({ payload, callback }, { call, put }) {
            /**
             * 企业登录的时候获取sessionwsid userwsid
             * 如果idttyWsid不存在就查阅企业的信息，获取idttywsid 第一次请求
             * 上传图片  //第二次请求
             * 查询企业信息 包含上传图片  第三次请求
             * 请求营业执照ocr识别 第四次请求
             * 上传完成
             */
            //查询企业的idttywsid
            let idttyWsid = payload.idttyWsid
            let reg = new RegExp(/0000$/, 'i')
            if(!idttyWsid) {
                //如果idttyWsid不存在就去请求
                let resBusinessInfo = yield call(getBusinessIdttyWsid, payload)
                let { code } = resBusinessInfo
                if(reg.test(code)) {
                    idttyWsid = resBusinessInfo?.enterpriseAccountAuthentication?.idttyWsid
                    //设置idttyWsid
                    yield put({
                        type: 'setIdttyWsid',
                        payload: idttyWsid
                    })
                } else {
                    let { message = '上传图片失败' } = resBusinessInfo
                    yield callback('error', message)
                    return
                }
            }
            let { file } = payload
            //就去上传图片
            let resImg = yield call(uploadImgBusinessLicense, {
                idttyWsid,
                file
            })
            let { resultData: { code } } = resImg
            if(reg.test(code)) {
                //如果上传图片成功就又去获取一次企业信息
                let resBusinessInfo = yield call(getBusinessIdttyWsid, payload)
                let { code } = resBusinessInfo
                if(reg.test(code)) {
                    //如果获取数据成功
                    let { enterpriseAccountAuthentication: { enterprise: { businessLicenseFileData } } } = resBusinessInfo
                    if(businessLicenseFileData !== null) {
                        let { base64 } = businessLicenseFileData
                        //OCR识别
                        let resOCR = yield call(OCRRecognition, file)
                        let { regNum, name, code } = resOCR
                        if(reg.test(code)) {
                            yield put({
                                type: 'changeBussinessInfoAndImgUrl',
                                payload: {
                                    regNum: regNum === '无' ? '' : regNum,
                                    name: name === '无' ? '' : name,
                                    imgUrl: base64
                                }
                            })
                            yield callback('success', '上传图片成功')
                        } else {
                            yield callback('error', '不支持的图片格式')
                        }
                    }
                } else {
                    let { message } = resBusinessInfo
                    yield callback('error', message)
                }
            } else {
                let { message } = resImg
                yield callback('error', message)
            }
        },
        //提交企业认证信息
        *submit({ payload, callback }, { call, put }) {
            /**
             * 1 提交企业认证信息拿到返回结果
             * 2 结果有正常操作和报错
             * 3 报错和认证失败都属于认证失败
             * 4 拿到结果后跳转结果页面
             */
            let res = yield call(submitEnterpriseInfo, payload)
            let { code, message } = res //拿到返回的结果
            let reg = new RegExp(/0000$/, 'i')
            if(reg.test(code)) {
                //可能失败也可能成功
                yield callback('normal', res)
            } else {
                //异常
                yield callback('abnormal', message)  //显示执行结果和跳转路由
            }
        },
        //查询企业信息获取已经上传的营业执照
        *getBusinessInfo({ payload, callback }, { call, put }) {
            /**
             * 1. 查询企业的Wsid和是否已经上传过图片
             * 2. 如果已经上传了图片，就去OCR验证
             * 3. 查询法人的姓名和身份证
             */
            let resBusinessInfo = yield call(getBusinessIdttyWsid, payload)
            let { code, message } = resBusinessInfo
            let reg = new RegExp(/0000$/, 'i')
            if(reg.test(code)) {
                let { enterpriseAccountAuthentication: { idttyWsid } } = resBusinessInfo
                let registerName = resBusinessInfo?.enterpriseAccount?.enterprise?.name
                yield put({
                    type: 'getRegisterName',
                    payload: registerName
                })
                //如果查询成功
                let { enterpriseAccountAuthentication: { enterprise: { businessLicenseFileData } } } = resBusinessInfo
                if(businessLicenseFileData) {
                    //如果存在数据
                    let { base64 } = businessLicenseFileData
                    let file = base64TOFile(base64, 'img')
                    let fd = new FormData()
                    fd.append('file', file)
                    let resOCR = yield call(OCRRecognition, fd)
                    let { regNum, name } = resOCR
                    yield put({
                        type: 'changeBussinessInfoAndImgUrl',
                        payload: {
                            regNum: regNum === '无' ? '' : regNum,
                            name: name === '无' ? '' : name,
                            imgUrl: base64,
                            idttyWsid
                        }
                    })
                }
            } else {
                yield callback('error', message)
                return
            }
            let { enterpriseAccount: { person: { name, idCardNo } } } = resBusinessInfo
            if(name && idCardNo) {
                yield put({
                    type: 'setLegalInfo',
                    payload: {
                        name,
                        idCardNo,
                    }
                })
                yield callback('success', '加载成功')
            } else {
                yield callback('error', '请检查是否经过实名认证')
            }
        }
    }
}
